package DAL.JDBC;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import DAL.Entites.UsedGame;

public class UsedGameJDBC {
	Connection conn;

	String tableName = "usedgames"; 

	public UsedGameJDBC(Connection connection) {
		this.conn = connection;
	}
	
	public boolean insert(int UserId, String Description, String Name) {
		// this is for selecting db incase we do insert first
		// ((DriverManagerDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/TestData");
		boolean result = false;
		
		String SQL = String.format("insert into %s values(null, %s,'%s', '%s', NOW())", tableName, UserId, Name, Description);
		
		try {
			Statement st = this.conn.createStatement();
			st.execute(SQL);
			System.out.println("Created Record");
			result = true;
			st.close();
		} 
		
		catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}
		
		return result;
	}
	
	private UsedGame mapRow(ResultSet rs) throws SQLException {
		UsedGame game = new UsedGame(
				rs.getInt("Id"), 
				rs.getString("Description"), 
				rs.getString("Name"), 
				rs.getInt("UserId"), 
				rs.getDate("CreateTime"));
		//user.SetPas(rs.getString("Address"));
		System.out.println("mapRow");

		return game;
	}
	
	public List<UsedGame> listUsedGames() {
		List<UsedGame> gameList = new ArrayList<UsedGame>();
		String SQL = String.format("select * from %s", tableName);
		try {
			Statement st = conn.createStatement();
			for (ResultSet rs = st.executeQuery(SQL); rs.next();) {
				gameList.add(mapRow(rs));
			}
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return gameList;
	}
	
	public boolean removeGame(int gameId) {
		boolean result = false;
		String SQL = String.format("delete from %s where Id = %s", tableName, gameId);
		try {
			Statement st = conn.createStatement();
			st.execute(SQL);
			result = true;
			st.close();
		} catch (SQLException ex) {
			System.err.println(ex.getMessage());
		}

		return result;
	}
}
